package com.czl.module_storehouse.adapter;

import android.annotation.SuppressLint;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.data.bean.tengyun.SortNumType;
import com.czl.base.util.SpHelper;
import com.czl.module_base.utils.NumberUtils;
import com.czl.module_storehouse.R;
import com.czl.module_service.system.Constants;

import java.util.List;

/**
 * @author xubin
 */
public class AddWareHouseAdapter extends BaseNumAdapter<SortBean> implements View.OnFocusChangeListener, View.OnTouchListener {

    private int mTouchItemPosition = -1;
    private final int mStorehouseLocationId = SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID);
    private final String locationName = SpHelper.INSTANCE.decodeString(Constants.SpKey.STOREHOUSE_LOCATION_NAME);
    /**
     * 判断是否是采购单或者工程入库
     */
    private boolean isOrder;

    public AddWareHouseAdapter(int layoutResId) {
        super(layoutResId);
    }

    public void setOrder(boolean order) {
        isOrder = order;
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, SortBean item) {
        item.setCount(item.getAddWarehouseNum());
        super.convert(helper, item);
        helper.setText(R.id.tv_model, item.getSortModel())
                .setText(R.id.tv_date, getDate(item))
                .setTextColor(R.id.tv_date, TextUtils.isEmpty(item.getManufactureDate()) ?
                        ContextCompat.getColor(getContext(), R.color.text_color_hint)
                        : ContextCompat.getColor(getContext(), R.color.color_333333))
                .setText(R.id.tv_add_name, item.getSortName())
                .setText(R.id.et_num, item.getPrice())
                .setText(R.id.et_vendor, item.getManufacturer())
                .setText(R.id.tv_product_loc, item.getLocText(isOrder, mStorehouseLocationId, locationName,
                        SortNumType.Type.NUM_TYPE_STOCK))
                .setText(R.id.tv_order_count, String.valueOf(item.getStorageNum()))
                .setVisible(R.id.tv_order_count, isOrder)
                .setVisible(R.id.ll_quantity, !isOrder)
                .setEnabled(R.id.et_num, !isOrder)
                .setVisible(R.id.tv_add_goods, (isOrder && (item.getSortId() == null || item.getSortId() == 0)))
                .setVisible(R.id.tv_remove, !isOrder)
                .setEnabled(R.id.et_vendor, (item.getSortId() != null && item.getSortId() > 0))
                .setEnabled(R.id.tv_date, (item.getSortId() != null && item.getSortId() > 0));
        helper.getView(R.id.tv_date).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AddWareHouseAdapter.this, v,
                        helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });
        helper.getView(R.id.tv_product_loc).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AddWareHouseAdapter.this, v,
                        helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });
        helper.getView(R.id.iv_right).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AddWareHouseAdapter.this, v,
                        helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });
        helper.getView(R.id.tv_add_goods).setOnClickListener(v -> {
            if (getOnItemChildClickListener() != null) {
                getOnItemChildClickListener().onItemChildClick(AddWareHouseAdapter.this, v,
                        helper.getLayoutPosition() - getHeaderLayoutCount());
            }
        });

        helper.getView(R.id.tv_remove).setOnClickListener(v -> remove(item));
        EditText etVendor = helper.getView(R.id.et_vendor);
        EditText etNum = helper.getView(R.id.et_num);
        setEditText(etVendor, helper.getLayoutPosition());
        setEditText(etNum, helper.getLayoutPosition());
    }

    private String getDate(SortBean bean) {
        if (bean == null) {
            return "请选择生产日期";
        }
        String manufactureDate = bean.getManufactureDate();
        if (TextUtils.isEmpty(manufactureDate)) {
            return "请选择生产日期";
        } else {
            return manufactureDate;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
    }

    public void setViewData(@IntRange(from = 0) int index, Object payload) {
        notifyItemChanged(index + getHeaderLayoutCount(), payload);
    }

    @Override
    public int getMaxCount(SortBean item) {
        return Integer.MAX_VALUE;
    }

    @Override
    public int getMinCount(SortBean item) {
        return item.getLocatTotalNum() == null ? 0 : item.getLocatTotalNum();
    }

    @Override
    protected void setAfterTextChanged(BaseViewHolder helper, SortBean item, int count) {
        if (item != null) {
            item.setDefaultLocat(count, mStorehouseLocationId, locationName, SortNumType.Type.NUM_TYPE_STORAGE);
            item.setStorageNum(count);
            helper.setText(R.id.tv_product_loc, item.getLocText(isOrder, mStorehouseLocationId, locationName, SortNumType.Type.NUM_TYPE_STOCK));
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setEditText(EditText editText, int position) {
        editText.setOnTouchListener(this);
        editText.setOnFocusChangeListener(this);
        editText.setTag(position - getHeaderLayoutCount());
        //保证每个时刻只有一个EditText能获取到焦点
        if (mTouchItemPosition != -1 && position == mTouchItemPosition) {
            editText.requestFocus();
        } else {
            editText.clearFocus();
        }
        editText.setSelection(editText.length());
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        EditText editText = (EditText) v;
        int id = editText.getId();
        if (id == R.id.et_vendor) {
            if (hasFocus) {
                editText.addTextChangedListener(mVendorTextWatcher);
            } else {
                editText.removeTextChangedListener(mVendorTextWatcher);
            }
        } else if (id == R.id.et_num) {
            if (hasFocus) {
                editText.addTextChangedListener(mPriceTextWatcher);
            } else {
                editText.removeTextChangedListener(mPriceTextWatcher);
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View view, MotionEvent event) {
        //onTouch 获取焦点
        if (event.getAction() == MotionEvent.ACTION_UP) {
            EditText editText = (EditText) view;
            mTouchItemPosition = (int) editText.getTag();
        }
        return false;
    }

    private final TextWatcher mVendorTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (mTouchItemPosition < getData().size()) {
                SortBean sortBean = getData().get(mTouchItemPosition);
                sortBean.setManufacturer(editable.toString());
            }
        }
    };

    private final TextWatcher mPriceTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String text = editable.toString();
            if (NumberUtils.isDouble(text)) {
                if (mTouchItemPosition < getData().size()) {
                    SortBean sortBean = getData().get(mTouchItemPosition);
                    sortBean.setPrice(text);
                }
            }
        }
    };
}
